package com.cntaiping.workutil.videoanalysis;

import com.cntaiping.analysis.domain.VideoAnalysisResult;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

public class DateTimeUtils {
    private static final Logger logger = LoggerFactory.getLogger(DateTimeUtils.class);

    /*
    获取当天所在一周的数据
    */
    public List<String> weekDateTime(Calendar instance, Date current){
        List<String> weekList = new ArrayList<>();

        Date start;
        Date end;


        int daysOfWeek = instance.get(Calendar.DAY_OF_WEEK) - 1;

        if(daysOfWeek == 0) {
            end = instance.getTime();

            instance.add(Calendar.DATE,-6);

            start = instance.getTime();

        }else {

            int weekFrom = 1 - daysOfWeek;
            int weekTo = 7 - daysOfWeek;

            instance.add(Calendar.DATE,weekFrom);

            start = instance.getTime();
            instance.setTime(current);
            instance.add(Calendar.DATE,weekTo);

            end = instance.getTime();
        }
        logger.info("the week begin:{},end:{}",DateFormatUtils.format(start,pattern),DateFormatUtils.format(end,pattern));

        instance.setTime(start);
        while (!instance.getTime().after(end)){
            weekList.add(DateFormatUtils.format(instance.getTime(),pattern));

            instance.add(Calendar.DATE,1);
        }



        return weekList;
    }

/*
获取往前10个工作日日期
*/
    public List<String> tenDateTime(Date current, Calendar instance) {
        List<String> ids = new ArrayList<>();
        instance.setTime(current);
        int num = 10;

        List<Integer> weeks = Arrays.asList(2,3,4,5,6);

        while (num > 0){
            int week = instance.get(Calendar.DAY_OF_WEEK);
            if(weeks.contains(week)) {
                num--;
                ids.add(DateFormatUtils.format(instance.getTime(),pattern));
            }
            instance.add(Calendar.DATE,-1);
        }
        return ids;
    }
    /*
    动态给实体类中的字段赋值
    */
    public void setMonthDay(Object count, VideoAnalysisResult result, String historyId) throws IllegalAccessException {

        Field[] declaredFields = count.getClass().getDeclaredFields();
        for (Field declaredField : declaredFields) {

            if (declaredField.getName().endsWith(historyId.substring(6))) {
                declaredField.setAccessible(true);
                declaredField.set(count, String.valueOf(result.getNum30()));
                return;
            }
        }
    }
}